import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 56. 合并区间
 * https://leetcode.cn/problems/merge-intervals/description/?envType=study-plan-v2&envId=top-100-liked
 */
class Solution2 {
    public int[][] merge(int[][] intervals) {
        int n = intervals.length;
        Arrays.sort(intervals, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> ret = new ArrayList<>();
        ret.add(intervals[0]);
        for(int i = 1; i < n; i++) {
            if(intervals[i][0] <= ret.get(ret.size() - 1)[1]) {
                //更新右边界
                ret.set(ret.size() - 1, new int[]{ret.get(ret.size() - 1)[0], Math.max(ret.get(ret.size() - 1)[1], intervals[i][1])});
            } else {
                //不用合并的情况
                ret.add(new int[]{intervals[i][0], intervals[i][1]});
            }
        }
        return ret.toArray(new int[ret.size()][]);
    }
}